from flask import request, render_template, redirect, url_for, jsonify, flash, session, make_response
from flask.views import MethodView, View
from .models import *
import hashlib
from datetime import datetime, timedelta
from .checklimit import check_limit


class Reg(MethodView):
    def get(self):
        return render_template('reg.html')

    def post(self):
        password = request.form.get('password')
        ha = hashlib.md5(b'j#$%&HG*R^&FD')
        ha.update(password.encode('utf-8'))
        haword = ha.hexdigest()
        userinfo = Admin(request.form.get('name'),
                         haword,
                         request.form.get('email'),
                         2,
                         datetime.now()
                         )
        db.session.add(userinfo)
        db.session.commit()
        name = dict(name=request.form.get('name'))
        return jsonify(name)


class CheckUser(MethodView):
    def get(self):
        name = request.args.get('name').lower()
        check = db.session.query(Admin).filter(Admin.name == name).one_or_none()
        return jsonify(check is None)


class EditUser(MethodView):
    def get(self):
        if check_limit() == 1:
            return redirect(url_for('admin.login'))
        if check_limit() == 2:
            return redirect(url_for('waring'))
        return render_template('edituser.html')

    def post(self):
        password = request.form.get('password')
        ha = hashlib.md5(b'j#$%&HG*R^&FD')
        ha.update(password.encode('utf-8'))
        oldpwd = ha.hexdigest()

        name = session.get('admin')
        newpwd = request.form.get('newpassword')
        check = db.session.query(Admin).filter(Admin.name == name, Admin.password == oldpwd).one_or_none()
        if check:
            ha = hashlib.md5(b'j#$%&HG*R^&FD')
            ha.update(newpwd.encode('utf-8'))
            haword = ha.hexdigest()
            check.password = haword
            db.session.commit()
            return jsonify(dict(num=1))
        else:

            return jsonify(dict(num=2))


class Login(MethodView):
    def get(self):
        return render_template('login.html')

    def post(self):
        rempwd = True if request.form.get('rempwd') == 'remember-me' else False
        name = request.form.get('name')
        password = request.form.get('password')
        ha = hashlib.md5(b'j#$%&HG*R^&FD')
        ha.update(password.encode('utf-8'))
        haword = ha.hexdigest()
        check = db.session.query(Admin).filter(Admin.name == name, Admin.password == haword).one_or_none()
        if check:
            session['admin'] = name
            if rempwd:
                resp = make_response(redirect(url_for('blog.blog_index')))
                resp.set_cookie('username', haword, expires=datetime.now() + timedelta(days=30))
                return resp
            return redirect(url_for('blog.blog_index'))
        else:
            flash('用户名或密码错误！')
            return render_template('login.html')


class LogOut(MethodView):
    def get(self):
        if request.cookies.get('username'):
            resp = make_response(redirect(url_for('.logout')))
            resp.set_cookie('username', '', expires=0)
            return resp
        if session.get('admin', None):
            session.pop('admin')

        return redirect(url_for('blog.blog_index'))
